package modules

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

type zapLog struct {
	logger      *zap.Logger
	sugarLogger *zap.SugaredLogger
}

var Logger zapLog

func (l *zapLog) NewSugaredLogger() *zap.SugaredLogger {
	if l.logger == nil {
		l.NewLogger()
	}
	if l.sugarLogger == nil {
		l.sugarLogger = l.logger.Sugar()
	}

	return l.sugarLogger
}

func (l *zapLog) NewLogger() *zap.Logger {
	if l.logger == nil {
		writeSyncer := l.getLogWriter()
		encoder := l.getEncoder()
		core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

		l.logger = zap.New(core, zap.AddCaller())
	}
	return l.logger
}

func (l *zapLog) getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func (l *zapLog) getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./test.log",
		MaxSize:    1,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}
